package cn.edu.imut.service;

import cn.edu.imut.bean.ProductBean;
import cn.edu.imut.bean.UserBean;
import cn.edu.imut.dao.AdminDao;
import cn.edu.imut.dao.ProductDao;
import cn.edu.imut.dao.UserDao;
import cn.edu.imut.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import java.util.Scanner;

public class AdminService {
    private final UserDao userDao = new UserDao();
    private final AdminDao adminDao = new AdminDao();
    private final ProductDao productDao = new ProductDao();
    private final Scanner sc = new Scanner(System.in);

    /**
     * 查看所有用户信息
     */
    public void viewAllUsers() {
        List<UserBean> users = userDao.getAllUsers();
        if (users.isEmpty()) {
            System.out.println("当前没有用户！");
        } else {
            users.forEach(System.out::println);
        }
    }

    /**
     * 更新用户权限
     */
    public void updateUserRole() {
        System.out.println("请输入要修改权限的用户ID：");
        int userId = sc.nextInt();
        System.out.println("请输入新的用户角色（user/vip/admin）：");
        String role = sc.next();

        if (userDao.updateUserRole(userId, role)) {
            System.out.println("用户权限更新成功！");
        } else {
            System.out.println("用户权限更新失败！");
        }
    }

    public boolean addNewProduct(String name, int categoryId, double price, int stock) {
        if (!isValidCategoryId(categoryId)) {
            System.out.println("无效的分类 ID，请重新输入！");
            return false;
        }

        String sql = "INSERT INTO gs_products (product_name, product_category, price, stock) VALUES (?, ?, ?, ?)";
        try (Connection connection = DBUtil.getConnection();
             PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setString(1, name);
            pstmt.setInt(2, categoryId);
            pstmt.setDouble(3, price);
            pstmt.setInt(4, stock);
            int rowsAffected = pstmt.executeUpdate();

            if (rowsAffected > 0) {
                System.out.println("新商品添加成功！");
                return true;
            }
        } catch (Exception e) {
            System.err.println("添加新商品时发生错误：" + e.getMessage());
        }
        return false;
    }
    public void addNewProduct() {
        Scanner sc = new Scanner(System.in);

        try {
            System.out.println("请输入商品名称：");
            String productName = sc.nextLine().trim();
            while (productName.isEmpty()) {
                System.out.println("商品名称不能为空，请重新输入：");
                productName = sc.nextLine().trim();
            }

            System.out.println("请输入分类ID（必须为正整数）：");
            int categoryId = getValidIntInput(sc);

            System.out.println("请输入商品价格（不能为负数）：");
            double price = getValidDoubleInput(sc);

            System.out.println("请输入库存数量（不能为负数）：");
            int stock = getValidIntInput(sc);

            // 创建新的商品对象
            ProductBean newProduct = new ProductBean(0, productName, categoryId, 0, price, stock);

            // 调用 DAO 层保存商品
            boolean result = productDao.addProduct(newProduct);

            if (result) {
                System.out.println("商品添加成功！");
            } else {
                System.out.println("商品添加失败，请重试！");
            }
        } catch (Exception e) {
            System.err.println("添加新商品时发生错误：" + e.getMessage());
            e.printStackTrace();
        }
    }

    // 获取有效的整数输入
    private static int getValidIntInput(Scanner sc) {
        while (true) {
            try {
                System.out.print("请输入：");
                int value = sc.nextInt();
                sc.nextLine(); // 消耗掉换行符
                return value;
            } catch (Exception e) {
                System.out.println("输入无效，请输入一个整数！");
                sc.nextLine(); // 清空缓冲区
            }
        }
    }

    // 获取有效的浮点数输入
    private static double getValidDoubleInput(Scanner sc) {
        while (true) {
            try {
                System.out.print("请输入：");
                double value = sc.nextDouble();
                sc.nextLine(); // 消耗掉换行符
                return value;
            } catch (Exception e) {
                System.out.println("输入无效，请输入一个有效的数字！");
                sc.nextLine(); // 清空缓冲区
            }
        }
    }



    public boolean isValidCategoryId(int categoryId) {
        String sql = "SELECT COUNT(*) FROM gs_categories WHERE category_id = ?";
        try (Connection connection = DBUtil.getConnection();
             PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setInt(1, categoryId);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                return rs.getInt(1) > 0; // 如果分类存在，返回 true
            }
        } catch (Exception e) {
            System.err.println("验证分类 ID 时发生错误：" + e.getMessage());
        }
        return false; // 分类不存在
    }



    /**
     * 下架商品
     */
    public void removeProduct() {
        System.out.println("请输入要下架的商品ID：");
        int productId = sc.nextInt();
        if (adminDao.removeProduct(productId)) {
            System.out.println("商品下架成功！");
        } else {
            System.out.println("商品下架失败！");
        }
    }

    /**
     * 编辑商品信息
     */
    public void editProductInfo() {
        System.out.println("请输入要编辑的商品ID：");
        int productId = sc.nextInt();
        System.out.println("请输入新的商品名称：");
        String newName = sc.next();
        System.out.println("请输入新的商品价格：");
        double newPrice = sc.nextDouble();

        if (adminDao.updateProductInfo(productId, newName, newPrice)) {
            System.out.println("商品信息更新成功！");
        } else {
            System.out.println("商品信息更新失败！");
        }
    }

    /**
     * 查询所有商品库存
     */
    public void displayAllStock() {
        List<ProductBean> products = adminDao.getAllStock();
        if (products.isEmpty()) {
            System.out.println("当前没有商品库存！");
        } else {
            System.out.println("以下是所有商品库存：");
            for (ProductBean product : products) {
                System.out.println("商品ID：" + product.getProductId());
                System.out.println("商品名称：" + product.getProductName());
                System.out.println("库存：" + product.getStock());
                System.out.println("--------------------------------");
            }
        }
    }

    /**
     * 调整商品库存
     */
    public void adjustStock() {
        System.out.println("请输入要调整的商品ID：");
        int productId = sc.nextInt();
        System.out.println("请输入新的库存数量：");
        int newStock = sc.nextInt();

        if (adminDao.updateStock(productId, newStock)) {
            System.out.println("商品库存更新成功！");
        } else {
            System.out.println("商品库存更新失败！");
        }
    }

    /**
     * 设置库存预警阈值
     */
    public void setStockThreshold() {
        System.out.println("请输入库存预警阈值：");
        int threshold = sc.nextInt();
        List<ProductBean> lowStockProducts = adminDao.getProductsBelowThreshold(threshold);
        if (lowStockProducts.isEmpty()) {
            System.out.println("没有商品低于设定的库存阈值：" + threshold);
        } else {
            System.out.println("以下是库存低于阈值的商品：");
            for (ProductBean product : lowStockProducts) {
                System.out.println("商品ID：" + product.getProductId());
                System.out.println("商品名称：" + product.getProductName());
                System.out.println("库存：" + product.getStock());
                System.out.println("--------------------------------");
            }
        }
    }


}
